package com.cn.shuangzi.loginplugin.common.socialized;

import com.cn.shuangzi.SZBaseActivity;
import com.cn.shuangzi.util.SZToast;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

/**
 * Created by CN on 2016/12/22.
 */

public class WeChatLogin {
    private IWXAPI iwxapi;
    private String wx_code = "";
    private SZBaseActivity activity;
    private ThirdLogin.OnThirdLoginResponseListener onThirdLoginResponseListener;

    public WeChatLogin(SZBaseActivity activity, ThirdLogin.OnThirdLoginResponseListener onThirdLoginResponseListener) {
        if(ThirdPlatform.WE_CHAT_APPID == null){
            throw new IllegalArgumentException("appId not init...");
        }
        this.activity = activity;
        this.onThirdLoginResponseListener = onThirdLoginResponseListener;
        iwxapi = WXAPIFactory.createWXAPI(activity, ThirdPlatform.WE_CHAT_APPID, true);
        iwxapi.registerApp(ThirdPlatform.WE_CHAT_APPID);
    }

    public void login() {
        if (iwxapi.isWXAppInstalled()) {
            iwxapi.registerApp(ThirdPlatform.WE_CHAT_APPID);
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
//            req.state = "wechat_sdk_demo_babyhome";
            iwxapi.sendReq(req);
        } else {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    SZToast.warning("微信未安装!");
                    onThirdLoginResponseListener.onFailed();
                }
            });
        }
    }

    public void setWx_code(String wx_code) {
        this.wx_code = wx_code;
    }

    public IWXAPI getIwxapi() {
        return iwxapi;
    }

    public void setIwxapi(IWXAPI iwxapi) {
        this.iwxapi = iwxapi;
    }

    public ThirdLogin.OnThirdLoginResponseListener getOnThirdLoginResponseListener() {
        return onThirdLoginResponseListener;
    }

    public void setOnThirdLoginResponseListener(ThirdLogin.OnThirdLoginResponseListener onThirdLoginResponseListener) {
        this.onThirdLoginResponseListener = onThirdLoginResponseListener;
    }

    public void onGetCodeSuccess() {
        if (onThirdLoginResponseListener != null) {
            onThirdLoginResponseListener.onSuccess(wx_code);
        }
    }

}
